<?php


function dbInit(){
     $link=mysqli_connect('localhost','root','','itcast');
     if(!$link){
         die('Connect Error (' . mysqli_connect_errno() . ') '
             . mysqli_connect_error());
     }
    mysqli_query($link,'set names utf8');
    mysqli_query($link,'use `itcast`');
}



function query($sql) {
    $link=mysqli_connect('localhost','root','','itcast');
    if ($result = mysqli_query($link,$sql)) {
        //执行成功
        return $result;
    } else {
        //执行失败
        echo 'SQL执行失败:<br>';
        echo '错误的SQL为:', $sql, '<br>';
        echo die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
        
    }
}


function fetchAll($sql) {

    //执行query()函数
    if ($result = query($sql)) {
        //执行成功
        //遍历结果集
        $rows = array();
        while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $rows[] = $row;
        }
        //释放结果集资源
        mysqli_free_result($result);
        return $rows;

    } else {
        //执行失败
        return false;
    }
}

function fetchRow($sql) {
    //执行query()函数
    if ($result = query($sql)) {
        //从结果集取得一次数据即可
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        return $row;
    } else {
        return false;
    }
}

function safeHandle($data){
    //转义字符串中的HTML标签
    $data = htmlspecialchars($data);
    //转义字符串中的特殊字符
    $data = mysqli_real_escape_string($data);
    return $data;
}
